package org.vaadin.example.views;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.login.LoginI18n;
import com.vaadin.flow.component.login.LoginOverlay;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.IntegerField;
import com.vaadin.flow.router.*;
import com.vaadin.flow.server.VaadinRequest;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import com.vaadin.flow.theme.lumo.LumoIcon;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.example.util.I18nUtil;
import org.vaadin.lineawesome.LineAwesomeIcon;
import org.vaadin.lineawesome.LineAwesomeIconUrl;

import java.util.List;
import java.util.Locale;
import java.util.UUID;

@Slf4j
@Route("login")

@PageTitle("Login | Vaadin CRM")
@AnonymousAllowed
public class LoginView extends VerticalLayout implements BeforeEnterObserver {
    private final LoginForm login ;

    Locale browserLocale = null;

    public LoginView(HttpServletRequest request, HttpServletResponse response) {



        String cokStr = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("myCookie".equals(cookie.getName())) {
                    System.err.println("LoginPage -Cookie Value: " + cookie.getValue());
                    cokStr = cookie.getValue();
                }
            }
        }


        if (cokStr==null && browserLocale == null){
            browserLocale = VaadinRequest.getCurrent().getLocale();
        }else {
            browserLocale =  new Locale(cokStr);
        }


//        Locale browserLocale = VaadinSession.getCurrent().getLocale();


        LoginI18n i18n = LoginI18n.createDefault();


        LoginI18n.Form i18nForm = i18n.getForm();
        i18nForm.setTitle(I18nUtil.getMessage("LogIn",browserLocale));
        i18nForm.setUsername(I18nUtil.getMessage("Username",browserLocale));
        i18nForm.setPassword(I18nUtil.getMessage("Password",browserLocale));
        i18nForm.setSubmit(I18nUtil.getMessage("LogInBtn",browserLocale));
        i18nForm.setForgotPassword(I18nUtil.getMessage("ForgotPassword",browserLocale));
        i18n.setForm(i18nForm);

        LoginI18n.ErrorMessage i18nLoginErrorMsg = i18n.getErrorMessage();
        i18nLoginErrorMsg.setTitle(I18nUtil.getMessage("i18nLoginErrorMsg.title",browserLocale));
        i18nLoginErrorMsg.setMessage(I18nUtil.getMessage("i18nLoginErrorMsg.message",browserLocale));
        i18nLoginErrorMsg.setUsername(I18nUtil.getMessage("i18nLoginErrorMsg.username",browserLocale));
        i18nLoginErrorMsg.setPassword(I18nUtil.getMessage("i18nLoginErrorMsg.password",browserLocale));
        i18n.setErrorMessage(i18nLoginErrorMsg);

        login = new LoginForm(i18n);

        addClassName("login-view");
        setSizeFull();
        setAlignItems(Alignment.CENTER);
        setJustifyContentMode(JustifyContentMode.CENTER);

        login.setAction("login");

//        login.addLoginListener(event -> {
//            String username = event.getUsername();
//            String password = event.getPassword();
//            log.info("Username :{},password:{} " , username,password);
//
//            //跳转到 hello 路由
//            getUI().ifPresent(ui -> ui.navigate("hello"));
//
//        });


        //改成combox  语言下拉框

        String changeLanguageText = I18nUtil.getMessage("changeLanguage", browserLocale);
        ComboBox<String> comboBox = new ComboBox<>(changeLanguageText);
        comboBox.setItems(List.of("English","中文"));
//        comboBox.setPrefixComponent(VaadinIcon.COG.create());
        comboBox.setPrefixComponent(LineAwesomeIcon.LANGUAGE_SOLID.create());
        //根据cookie - browserLocale set comboBox.setValue
        if (browserLocale.toString().contains("en")){
            comboBox.setValue("English");
        }else {
            comboBox.setValue("中文");
        }
        comboBox.addValueChangeListener(event->{
            String value = event.getValue();
            System.err.println(value);
            if ("English".equals(value)) {
                Cookie cookie = new Cookie("myCookie", Locale.US.toString());
                cookie.setPath("/");
                cookie.setMaxAge(60 * 60); // Set the cookie to expire in 1 hour
                response.addCookie(cookie);

                UI.getCurrent().getPage().reload();
            }else {
                Cookie cookie = new Cookie("myCookie", Locale.CHINA.toString());
                cookie.setPath("/");
                cookie.setMaxAge(60 * 60); // Set the cookie to expire in 1 hour
                response.addCookie(cookie);


                UI.getCurrent().getPage().reload();

            }
        });

//        com.vaadin.flow.component.button.Button test = new com.vaadin.flow.component.button.Button("test", e -> {
//            Cookie cookie = new Cookie("myCookie", Locale.US.toString());
//            cookie.setPath("/");
//            cookie.setMaxAge(60 * 60); // Set the cookie to expire in 1 hour
//            response.addCookie(cookie);
//            UI.getCurrent().getPage().reload();
//        });


        String systemNameText = I18nUtil.getMessage("SystemName", browserLocale);
        add(new H1(systemNameText), login,comboBox);
    }

    @Override
    public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
        // 生成一个新的traceId
        String traceId = UUID.randomUUID().toString();
        // 将traceId存储在session中
        UI.getCurrent().getSession().setAttribute("traceId", traceId);

        // inform the user about an authentication error
        if (beforeEnterEvent.getLocation()
                .getQueryParameters()
                .getParameters()
                .containsKey("error")) {
            login.setError(true);
        }
    }




}
